package cn.hd01.web.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.hd01.repository.entity.User;
import cn.hd01.repository.entity.WXOauth;

public class WebHelper implements WebConstant {
	public static final int PORT = 80;

	public static HttpServletRequest request() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static HttpSession session() {
		return request().getSession();
	}

	public static String fullUrl() {
		HttpServletRequest request = request();
		StringBuffer basePath = new StringBuffer();

		basePath.append(request.getScheme());
		basePath.append("://");
		basePath.append(domain());
		basePath.append(request.getRequestURI());

		if (StringUtils.hasText(request.getQueryString())) {
			basePath.append("?");
			basePath.append(request.getQueryString());
		}

		return basePath.toString();
	}

	public static String basePath() {
		HttpServletRequest request = request();
		StringBuffer basePath = new StringBuffer();

		basePath.append(request.getScheme());
		basePath.append("://");
		basePath.append(domain());
		basePath.append(request.getContextPath());

		return basePath.toString();
	}

	public static String domain() {
		HttpServletRequest request = request();

		StringBuffer sb = new StringBuffer(request.getServerName());
		if (PORT != request.getServerPort()) {
			sb.append(":");
			sb.append(request.getServerPort());
		}

		return sb.toString();
	}

	@SuppressWarnings("unchecked")
	public static <T> T sessionAttr(String name, Class<T> clazz) {
		return (T) session().getAttribute(name);
	}

	public static <T> T getAndRemoveSessionAttr(String name, Class<T> clazz){
		T value = (T) session().getAttribute(name);
		session().removeAttribute(name);
		return value;
	}

	public static User currentUser() {
		return sessionAttr(WebConstant.USER_SESSION_NAME, User.class);
	}

	public static WXOauth currentWXOauth() {
		return sessionAttr(WebConstant.USER_SESSION_NAME, WXOauth.class);
	}
}
